/*
 * @Descripttion: 
 * @Author: cuidm
 * @Date: 2022-07-13 09:26:36
 * @LastEditors: cuidm
 * @LastEditTime: 2022-10-21 12:01:09
 */

import React, { useEffect, useState } from "react";
import { Affix, Button, Alert, Radio, Select, Input, Space, Row, Col, Tree, message, Spin, Empty } from "antd";
import { DownCircleOutlined, RightCircleOutlined, UploadOutlined, SearchOutlined } from "@ant-design/icons";
import { TempImportModal} from "@/components";
import request, { exportFile } from "@/utils/request";
import cmdbres from "@/data/cmdbres";
import hcpUtils from '@/utils/hcpUtils';
import "./index.less";

const ModelTree = ({ history, match, location, moduleId, setSelectTreeNode }) => {
    const [loading, setLoading] = useState(true);
    const [expandedKeys, setExpandedKeys] = useState([]);
    const [selectedKeys, setSelectedKeys] = useState([]);
    const [allTreeData, setAllTreeData] = useState([]);
    const [treeData, setTreeData] = useState([]);
    const [autoExpandParent, setAutoExpandParent] = useState(true);
    
    const [info, setInfo] = useState({});
    const [searchValue, setSearchValue] = useState('');
    
    const renderTitle = (item) => {
        const {name, type} = item;
        const strTitle = item.name;
        const index = strTitle?.indexOf(searchValue);
        const beforeStr = strTitle?.substring(0, index);
        const afterStr = strTitle?.slice(index + searchValue.length);
          
        return (
            <>
                <span className="node-name" title={name}>
                    {
                        index > -1 ? (
                        <span>
                            {beforeStr}
                            <span className="tree-search-value">{searchValue}</span>
                            {afterStr}
                        </span>
                        ) : (
                        <span>{strTitle}</span>
                        )
                    }
                </span>
            </>
        )
    }

    const queryModel = async () => {
        try {
            setLoading(true);
            let res = await request({
                ...cmdbres.queryModelList,
                params: {
                    namespace: "default",
                },
            });
            
            if (res && res.code == 200) {
                let defaultSelectedKey = moduleId;
                let defaultSelectedNode = null;
                let arr = [];//tree扁平化
                let moduleIcons = {};
                hcpUtils.treeDataIteration(res.data, function (item) {
                    if(item.cmModuleId) { //是模型
                        item.key = item.cmModuleId;
                        item.name = item.moduleName;
                        item.icon = <span className={`iconfont ${item.moduleIcon}`}></span>;
                        item.type = "module";
                        item.parentKey = item.moduleClassificationId;
                        moduleIcons[item.cmModuleId] = item.moduleIcon;
                    } else { //是分组
                        item.key = item.id;
                        item.name = item.moduleClassificationName;
                        item.type = item.parentId ? "secondary" : "top";//顶级和次级分组
                        if(!(item.definitions && item.children)) {
                            item.switcherIcon = null;
                        }
                        item.parentKey = item.parentId || 0;
                        item.icon = null;
                    }

                    if(defaultSelectedKey && item.cmModuleId == defaultSelectedKey) {
                        defaultSelectedNode = item;
                    }
                    if(item.definitions && item.definitions.length) {
                        item.children = item.children ? item.children.concat(item.definitions) : item.definitions;
                        if(!defaultSelectedKey) {
                            defaultSelectedKey = item.definitions[0].cmModuleId;
                            defaultSelectedNode = item.definitions[0];
                        };
                        delete item.definitions; 
                    }

                    arr.push({
                        key: item.key,
                        title: item.name
                    });
                    item.displayName = item.name;
                    item.title = renderTitle(item);
                });
                setExpandedKeys([defaultSelectedKey]);
                setSelectedKeys([defaultSelectedKey]);
                setSelectTreeNode(defaultSelectedNode);
                let filterCode = ['biz_topology_group','business_group'];
                res.data = res.data.filter(item => !filterCode.includes(item.moduleClassificationCode));

                setTreeData(res.data);
                setAllTreeData(arr);
                localStorage.setItem('moduleIcons', JSON.stringify(moduleIcons));
            }
            setLoading(false);
        } catch (error) {
            console.log(error);
        }
    }

    useEffect(() => {
        queryModel();
    }, [])

    const onExpand = (keys) => {
        setExpandedKeys(keys);
        setAutoExpandParent(false);
    };

    const onSelect = (selectedKeys, e) => {
        if(e.node.type == "module") {
            setSelectedKeys(selectedKeys);
            if(setSelectTreeNode) {
                setSelectTreeNode(e.node);
            };
            return;
        }
        // 对expandedKeys进行拷贝
        let copyExpandedKeys = [...expandedKeys];
        // 节点处于未展开状态
        if (!e.node.expanded) {
          // 将节点key值存入到expandedKeys中
          copyExpandedKeys.push(e.node.key);
          setExpandedKeys(copyExpandedKeys);
        }
        // 节点处于已展开状态
        else {
          // 获取被点击节点key在expandedKeys中的下标值
          let expandedIndex = copyExpandedKeys.indexOf(e.node.key);
          // 将节点的key从expadedKeys中移除
          copyExpandedKeys.splice(expandedIndex, 1);
          setExpandedKeys(copyExpandedKeys);
        }
    };

    const getParentKey = (key, tree) => {
        let parentKey;
      
        for (let i = 0; i < tree.length; i++) {
          const node = tree[i];
      
          if (node.children) {
            if (node.children.some((item) => item.key === key)) {
              parentKey = node.key;
            } else if (getParentKey(key, node.children)) {
              parentKey = getParentKey(key, node.children);
            }
          }
        }
      
        return parentKey;
      };

    const onChange = (e) => {
        const { value } = e.target;
        const newExpandedKeys = allTreeData
          .map((item) => {
            if (item.title.indexOf(value) > -1) {
              return getParentKey(item.key, treeData);
            }
    
            return null;
          })
          .filter((item, i, self) => item && self.indexOf(item) === i);
        setExpandedKeys(newExpandedKeys);
        setSearchValue(value);
        setAutoExpandParent(true);
    };

    const loop = (data) =>
        data.map((item) => {
        if (item.children) {
            return {
                ...item,
                title: renderTitle(item),
                children: loop(item.children),
            };
        }

      return {
        ...item,
        title: renderTitle(item),
        key: item.key,
      };
    });

    useEffect(() => {
        const arr = loop(treeData);
        setTreeData(arr);
    }, [searchValue])

    return (
        <div className="tree-box">
            <Input
                className="tree-search"
                placeholder="请输入模型名称"
                value={searchValue}
                onChange={onChange}
                style={{ marginBottom: 10 }}
                suffix={<SearchOutlined />}
            />
            {loading ? <Spin className="module-tree-spin"/>:
            treeData.length ? 
                <Tree
                    className="module-view-tree"
                    showLine
                    showIcon
                    showLeafIcon={false}
                    // switcherIcon={<DownCircleOutlined />}
                    expandedKeys={expandedKeys}
                    selectedKeys={selectedKeys}
                    treeData={treeData}
                    onSelect={onSelect}
                    onExpand={onExpand}
                    autoExpandParent={autoExpandParent}
                    // defaultExpandParent
                />
                : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            }
        </div>
    )
}

export default ModelTree;
